/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name:server.c
> Author:xxx
> Mail: 
> Created Time: 2024年12月04日 星期三 09时18分10秒
***************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <mysql/mysql.h>
#include <sys/epoll.h>
#include "style.h"

int main(int argc,const char* argv[])
{
	//创建服务器套接字
	int server_socket = socket(AF_INET,SOCK_STREAM,0);
	printf("%d\n",server_socket);
	
	struct sockaddr_in  saddr;
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(6666);
	saddr.sin_addr.s_addr = inet_addr("192.168.0.195");
	
	int optval = 1;
	setsockopt(server_socket,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(optval));
	//服务器绑定主机
	bind(server_socket,(struct sockaddr *)&saddr,sizeof(saddr));
	
	//启动监听
	listen(server_socket,10);
	printf("监听已启动\n");
	
	//创建epoll监听
	int ep = epoll_create(1);
	
	struct epoll_event ev;
	ev.events = EPOLLIN;
	ev.data.fd = server_socket;
	//将server_socket加入监听
	epoll_ctl(ep,EPOLL_CTL_ADD,server_socket,&ev);
	
	//创建句柄
	MYSQL mysql;
	//初始化
	mysql_init(&mysql);
	//连接数据库
	MYSQL *flag;
	flag = mysql_real_connect(&mysql,"localhost","root","1","guest",0,NULL,0);
	if(flag == NULL){
		printf("%s\n",mysql_error(&mysql));
	}
	
	int num = 0;
	int i = 0;
	struct sockaddr_in caddr;
	int len = sizeof(caddr);
	struct epoll_event events[10];
	char buf[1024] = {0};
	while(1){
		//阻塞监视ep中的文件描述符,返回值为发生事件的个数
		num = epoll_wait(ep,events,10,5000);
		printf("%d\n",num);
		for(i = 0;i < num;i++){
			int fd = events[i].data.fd;
			if(fd == server_socket){
				//如果是有客户端连接，则创建一个新的通信套接字
				int client_socket = accept(server_socket,(struct sockaddr *)&caddr,&len);
				printf("ip:%s,port:%d\n",inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port));
				ev.events = EPOLLIN | EPOLLET;
				ev.data.fd = client_socket;
				//将client_socket加入监听
				epoll_ctl(ep,EPOLL_CTL_ADD,client_socket,&ev);
			}else{
				int flag = fcntl(fd,F_GETFL);
				flag |= O_NONBLOCK;
				fcntl(fd,F_SETFL,flag);
				
				read(fd,buf,sizeof(buf));
				printf("%s\n",buf);
				int type = cjson_type(buf);
				if(type == 1){
					gly_login(fd,buf);
				}else if(type == 2){
					
				}else if(type == 3){
					
				}else if(type == 4){
					
				}
			}
		}
		
	}
	close(server_socket);
	
    return 0;
}
